package com.gitee.feizns.explore.data_structure.tree.bs.easy;

/**
 * 671. 二叉树中第二小的节点
 * @author feizns
 * @since 2020/1/4
 */
public class FindSecondMinimumValue {

    public static void main(String[] args) {
        System.out.println(findSecondMinimumValue(create()));
    }

    private static TreeNode create() {
        TreeNode ret = new TreeNode(5);
        ret.left = new TreeNode(5);
        ret.right = new TreeNode(6);
        return ret;
    }

    public static int findSecondMinimumValue(TreeNode root) {
        return unique(root, root.val);
    }

    private static int unique(TreeNode root, int min) {
        if ( root != null ) {
            if ( root.val != min )
                return root.val;
            int l = unique(root.left, min);
            int r = unique(root.right, min);
            if ( l != -1 && r != -1 )
                return Math.min(l, r);
            else if ( l == -1 )
                return r;
            else
                return l;
        }
        return -1;
    }

}
